library(shiny)
library(readr)

data <- read_csv2("data/amostra.csv")
brasil <- read_csv2("data/brasil.csv")
acidentes <- read_csv2("data/acidentes.csv")

sct_data <- as.matrix(data[ , c("hora_acidente", "idade_cat", "ds_agente_causador")])

bar_data <- read_csv2("data/teste.csv")

choropleth_data <- read_csv2("data/puf.csv")

parallelcoordinates_data <- read_csv2("data/acidentes-sumarizado.csv")

radarchart <- read_csv2("data/uf-municipio.csv")

radarchart_data <- list(
    list(
        list(axis = "2012", value = 3),
        list(axis = "2013", value = 6),
        list(axis = "2014", value = 8),
        list(axis = "2015", value = 3),
        list(axis = "2016", value = 3))
)

radarchart_data1 <- read_csv2("data/ac_ano_radarchart.csv")
                                        # TODO rename functions
# This one generates a list for a tree or dendrogram
rsplit <- function(x) {
  if(ncol(x) > 1) {
      listSplit <- split(x[-c(1)], x[1], drop=F)
      lapply(names(listSplit), function(y) {list(name = y,
                                                 children = rsplit(listSplit[[y]]))})
  } else {
      lapply(seq(nrow(x[1])), function(y) {list(name = as.character(x[y,1]))})
  }
}

# This one generates a list for a treemap
makeList <- function(x) {
  if(ncol(x) > 2) {
      listSplit <- split(x[-c(1)], x[1], drop=F)
      lapply(names(listSplit), function(y) {list(name = y,
                                                 value = as.integer(listSplit[[y]][1,1]),
                                                 children = makeList(listSplit[[y]][-1]))})
  } else {
      lapply(seq(nrow(x[1])), function(y) {list(name = as.character(x[y,1]),
                                                value = as.integer(x[y,2]))})
  }
}

treemap_data <- makeList(unique(acidentes))

tree_data <- rsplit(unique(brasil))[[1]]

server <- function(input, output, session) {

    observe({

        session$sendCustomMessage(type="scatterplot_values", message = sct_data)

    })

    observe({

        session$sendCustomMessage(type="dendrogram_values",
                                  message = c(tree_data, bar_data))

    })

    observe({

        session$sendCustomMessage(type="treemap2_values", message = treemap_data)

    })


    observe({

        session$sendCustomMessage(type="choropleth_values", message = choropleth_data)

    })

    observe({

        session$sendCustomMessage(type="parallelcoordinates_values", message = parallelcoordinates_data)

    })

    observe({

        session$sendCustomMessage(type="radarchart_values", message = list(radarchart_data, radarchart_data1))

    })
}
